//
//  XML_Bloomberg_History.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/2/27.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//
#import "XX_XQData_History.h"
#import "XML_Bloomberg_History.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBall.h"

@implementation XML_Bloomberg_History
@synthesize delgeate;
-(id)init_With_Code:(NSString *)codea file_code:(NSString *)file_code table_quote_date:(NSDate *)dateq timezone:(NSString *)tz    is_have_to_reload_data:(BOOL)have_to_reload{
	
    if(self=[super init])
	{
        
        have_to_reload_data=have_to_reload; 
        
        
        code=codea;
        read_write_file_code=file_code;
        table_quote_date=dateq;
        timezone=tz;  
        
        [code retain];
        [read_write_file_code retain];
        [table_quote_date retain];
        [timezone retain];
    
    }
	
	return self;
}

-(void)dealloc{
    if (code) {
          [code release]; 
    }
    if (read_write_file_code) {
        // [read_write_file_code release];
    }
    if (table_quote_date) {
           [table_quote_date release];
    }
    if (timezone) {
        [timezone release];
    }
    
    
    [super dealloc];
}

- (void)main 
{ 
   
    if (have_to_reload_data) {
        
        
        //NSLog(@"XML_Bloomberg_History_main_his_Start=%@ %@",read_write_file_code,code);
        
        if ( [read_write_file_code hasPrefix:@"NA_Code"]) {
            read_write_file_code= code  ;
        }
        
        //代碼間的分隔號 ：要替換
        read_write_file_code=[read_write_file_code stringByReplacingOccurrencesOfString:@":" withString:@"_"];
        
        
        //將歷史資料檔案陣列 最大值 最小值 存放在Dictionary，用來傳出去
        //NSMutableDictionary *out_dic;    
        
        //此程式要取出的資料 :歷史資料 最大值 最小值
        NSMutableDictionary *outarray_his_data; //歷史資料
        NSMutableArray      *outarray_his_array; //歷史資料    
        //outarray_his_data=[[[NSMutableArray alloc] init] autorelease];
        float his_data_high; // 最大值
        float his_data_low;  // 最小值 
        his_data_low=0;
        his_data_high=0;
        
        
        //歷史檔案路徑
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
        NSString *Path_HistoryData  ; 
        Path_HistoryData=[prefs objectForKey:Defaults_Path_HistoryData];  
        
        NSString *filename;
        filename=[NSString stringWithFormat: @"%@.plist",read_write_file_code];
        NSString * write_FilepathnName= [Path_HistoryData stringByAppendingPathComponent:filename]  ;          
        
        //NSLog(@"write_FilepathnName=%@",write_FilepathnName );
        
        
        //檢查是否有歷史資料檔案    
        NSFileManager *fileManager = [NSFileManager defaultManager];                                
        BOOL success = [fileManager fileExistsAtPath:write_FilepathnName];
              
        //如果有xq資料
        if ([XX_XQData_History isHaveXQ_Dairly_Data:read_write_file_code]) {
             
            
             outarray_his_data=[XX_XQData_History read_XQ_Dairly_Data:read_write_file_code _code:code _timezone:timezone];
            
             //outarray_his_array=[outarray_his_data objectForKey:@"his_data"];
            
        }
        //原始的資料
        else if (success) {
            NSLog(@"有檔案");
            //網路上取出一個月的資料來比對
            NSDictionary *check_data;
            NSDate *check_last_date;
            NSNumber *check_last_close;
            NSMutableArray *check_his_data;
            
            check_data= [self GET_Bloomberg_History_Data:@"1M"]; //取一個月資料
            check_last_date=[check_data objectForKey:@"last_his_date"] ;
            check_last_close=[check_data objectForKey:@"last_his_close"];
            check_his_data=[check_data objectForKey:@"his_data"];
            
            NSLog(@"網路上_目前最後一筆資料_日期=%@",check_last_date);
            NSLog(@"網路上_目前最後一筆資料_收盤價=%@",check_last_close);         
            
            
            //從檔案上取出歷史資料檔案
            outarray_his_data=[NSDictionary  dictionaryWithContentsOfFile:  write_FilepathnName]; 
            outarray_his_array=[outarray_his_data objectForKey:@"his_data"];
            
            NSDate *file_last_date;
            NSNumber *file_last_close;        
            
            
            //歷史檔案正確
            file_last_date=  [outarray_his_data objectForKey:@"last_his_date" ] ;   
            file_last_close=[outarray_his_data objectForKey:@"last_his_close"] ; 
            
            NSLog(@"檔案上_目前最後一筆資料_日期=%@",file_last_date);
            NSLog(@"檔案上_目前最後一筆資料_收盤價=%@",file_last_close);           
            
            //開始循環進入篩選
            BOOL have_check;//判斷此循環內：歷史檔案與網路上資料日期是否有相同過 如果沒有表示檔案資料應該超過一個月
            have_check=NO;
            
            BOOL need_add_his_data;
            need_add_his_data=NO;
            
            int  timeStamp_file_last_date;
            int  timeStamp_his_data_last_date;
            
            timeStamp_file_last_date=0;
            timeStamp_his_data_last_date=0;        
            for (NSDictionary *dic_check in check_his_data) {
                
                NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
                dateFormatters.dateFormat = @"yyyyMMdd";
                [dateFormatters setTimeZone: [NSTimeZone   timeZoneWithName:timezone]];
                timeStamp_file_last_date = [[dateFormatters stringFromDate:file_last_date] intValue];                
                timeStamp_his_data_last_date = [[dateFormatters stringFromDate:[dic_check objectForKey:HIS_basic_date] ] intValue];            
                
                [dateFormatters release];
                
                int  diff_day_last_quote_his=timeStamp_file_last_date-timeStamp_his_data_last_date;                        
                
                if (need_add_his_data==YES) {
                    //資料開始添加
                    NSLog(@"**資料開始添加=%@",[dic_check objectForKey:HIS_basic_date] );
                    
                    [outarray_his_array  addObject:dic_check];  
                    [outarray_his_data setObject:[dic_check objectForKey:HIS_basic_date ] forKey:@"last_his_date"];
                    [outarray_his_data setObject:[dic_check objectForKey:HIS_basic_close ] forKey:@"last_his_close"];                
                }
                
                
                
                if (diff_day_last_quote_his==0) {
                    NSLog(@"相等的日期=%@",file_last_date);
                    //檢查收盤價是否差異超過0.01
                    float check_close;
                    float file_close;
                    check_close=[[dic_check objectForKey:HIS_basic_close] floatValue];
                    file_close=[file_last_close floatValue];
                    NSLog(@"close= %f %f" ,check_close , file_close);
                    if ( fabs(check_close -file_close) >=0.1  ) {
                        NSLog(@"狀況一(有檔案):有檔案但是收盤價差值超過0.1 需要重新下載資料");
                        //狀況一(有檔案):兩這資料差異太大 需要重新下載資料
                        outarray_his_data=   [self GET_Bloomberg_History_Data:@"5Y"]  ;                       
                    }
                    else {
                        NSLog(@"狀況二(有檔案)：兩這資料接近,開始往後的資料添加進去"); 
                        //狀況二(有檔案)：兩這資料接近,開始往後的資料添加進去 不過本日不添加 要等到下一期添加
                        need_add_his_data=YES;
                    }
                    have_check=YES;
                }
                
                
                
                
            }
            
            //檔案上的日期大於網路上的檢查日期 則不需要重新下載   
            if (timeStamp_file_last_date>timeStamp_his_data_last_date) {
                NSLog(@"檔案上的日期大於網路上的檢查日期 則不需要重新下載");
                have_check=YES;
            }
            
            
            
            if (have_check==NO) {
                //狀況三(有檔案):檔案上的資料超過一個月 需要全部重新下載資料
                NSLog(@"狀況三(有檔案):檔案上的資料超過一個月 需要全部重新下載資料");
                outarray_his_data=  [self GET_Bloomberg_History_Data:@"5Y"] ;             
                
            }
            
            //最後再次重新整理計算統計數值
            {
                BOOL issetHighLow;
                issetHighLow=NO;  
                
                for (NSDictionary *dicd in  outarray_his_array   ) {
                    
                    
                    if (issetHighLow==NO) {
                        //第一次設定
                        his_data_low=[[dicd objectForKey:HIS_basic_close] floatValue ];
                        his_data_high=[[dicd objectForKey:HIS_basic_close] floatValue ];
                        issetHighLow=YES;
                    }
                    if ([[dicd objectForKey:HIS_basic_high] floatValue ]>his_data_high) {
                        his_data_high=[[dicd objectForKey:HIS_basic_high] floatValue ];
                    }
                    if ([[dicd objectForKey:HIS_basic_low] floatValue ]<his_data_low) {
                        his_data_low=[[dicd objectForKey:HIS_basic_low] floatValue ];
                    }           
                    file_last_date=[dicd objectForKey:HIS_basic_date];
                    file_last_close=[dicd objectForKey:HIS_basic_close];
                } 
                
                
                [outarray_his_data setObject:code forKey:DB_object_sqlite_basic_code];
                [outarray_his_data setObject:[NSNumber numberWithFloat:his_data_high] forKey:@"his_data_high"];
                [outarray_his_data setObject:[NSNumber numberWithFloat:his_data_low] forKey:@"his_data_low"];                
                [outarray_his_data setObject:file_last_date forKey:@"last_his_date"]; 
                [outarray_his_data setObject:file_last_close forKey:file_last_close];             
            }
            
            
        }
        else {
            //狀況四(有檔案):全部下載資料
            NSLog(@"狀況四(無檔案):全部下載資料"); 
            
            //從網路上取出全新的歷史資料 及其它最高最低 及其他資料 
            outarray_his_data= [self GET_Bloomberg_History_Data:@"5Y"];
            
            
        }
        //取出歷史資料後的動作
        {
            //1.儲存檔案
            {
                
                
                
                [outarray_his_data writeToFile:write_FilepathnName atomically:YES];
                
            }
            /*
             {
             NSString *error;
             NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:outarray_his_data format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
             if(xmlData)
             {
             NSLog(@"No error creating XML data.");
             [xmlData writeToFile:write_FilepathnName atomically:YES];
             }
             else
             {
             // NSLog(error);
             [error release];
             }        
             }
             */
            
            //2.將整理好的開收高低成交量資料傳出來
            [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished:) withObject:outarray_his_data waitUntilDone:YES];        
            
            //   [outarray_his_data release];    
        }        
        
    }
    else {
        
        NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
        [out_dic setObject:code forKey:DB_object_sqlite_basic_code];        
        [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished_not_reload:) withObject:out_dic waitUntilDone:YES];     
    }
    
    
   
    
   
}

-(NSMutableDictionary *)GET_Bloomberg_History_Data:(NSString *)time_period{
    
    NSMutableArray *outarray_his_data; //歷史資料
    outarray_his_data=[[[NSMutableArray alloc] init] autorelease];
    
    double his_data_high; // 最大值
    double his_data_low;  // 最小值 
    his_data_low=0;
    his_data_high=0;    
    
    NSDate *last_his_date=[NSDate dateWithTimeIntervalSince1970:9999];
    NSNumber *last_his_close=[NSNumber numberWithFloat: 0 ]; 
    
    
    //從網路上取出全新的資料
    //1.設定 ＵＲＬ注意事項： %%   (iPhone%%20OS)  
    NSString *urls_his= [NSString stringWithFormat: @"http://m.bloomberg.com/iphone/apps/data.asp?pid=webpxta&Securities=%@&TimePeriod=%@&Outfields=HDATE,PR005-H,PR006-H,PR007-H,PR008-H,PR013-H&bbipver=1.0.9,%@,iPad,iPhone%%20OS,%@,zh_TW,zh-Hant",code,time_period,UDID,OS_Version];
    
    //2.轉成 NSURL
    NSURL *url = [NSURL URLWithString:urls_his];   
    
    
    //3.製作request
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                    autorelease];
    
    [request setValue:Bloomberg_User_Agent forHTTPHeaderField:@"User-Agent"];
    [request setValue:Bloomberg_Pragma forHTTPHeaderField:@"Pragma"];    
    
    
    //4.下載data
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
    //5.data 資料轉成string
    NSString  *download_string_bloomberg;
    download_string_bloomberg = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];    
    
    
    //6.針對下載文字資料進行分解
    NSArray *csvLines = [download_string_bloomberg  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    
    
    [download_string_bloomberg release];
    
    
    BOOL issetHighLow;
    issetHighLow=NO;
    
    for (NSString *line in csvLines ) {
        
        if ([line hasPrefix:@"HistoryData"]) {
            //NSLog(@"標頭=%@",line);
        }
        else if ([line hasPrefix:@"="]) {
            //NSLog(@"結束");
        }
        else if(![line isEqualToString:@""]){
            //NSLog(@"資料=%@",line);
            
            NSArray *pdata = [line componentsSeparatedByString:@"\""]   ;
            if ([pdata count]==6) {
                NSMutableDictionary *dic;
                dic=[[NSMutableDictionary alloc] init]; 
                
                
                NSDate *dates;
                
               
                
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                [dateFormatter setDateFormat:@"yyyyMMdd"];
                 [dateFormatter setTimeZone: [NSTimeZone   timeZoneWithName:timezone]];
                dates = [dateFormatter dateFromString:[pdata objectAtIndex:0] ];
               [dateFormatter release];                 
                
                NSNumber *close=[NSNumber numberWithDouble:[[pdata objectAtIndex:1] doubleValue ]];
                //NSLog(@"close=%@ %@",[pdata objectAtIndex:1],[close stringValue]  );
                                   
                NSNumber *open;
                if ([[pdata objectAtIndex:2] doubleValue]==0) {
                    open=[NSNumber numberWithDouble:[[pdata objectAtIndex:1] doubleValue ]];
                }
                else{
                   open=[NSNumber numberWithDouble:[[pdata objectAtIndex:2] doubleValue]];
                }
               
                
                NSNumber *high;
                if ([[pdata objectAtIndex:3] doubleValue]==0) {
                    high=[NSNumber numberWithDouble:[[pdata objectAtIndex:1] doubleValue ]];
                }
                else{
                    high=[NSNumber numberWithDouble:[[pdata objectAtIndex:3] doubleValue ]];
 
                } 
                
                NSNumber *low;
                if ([[pdata objectAtIndex:4] doubleValue]==0) {
                    low=[NSNumber numberWithDouble:[[pdata objectAtIndex:1] doubleValue ]];
                }
                else{
                    low=[NSNumber numberWithDouble:[[pdata objectAtIndex:4] doubleValue ]];
                    
                } 
                
                NSNumber *volume=[NSNumber numberWithInt:[[pdata objectAtIndex:5] intValue ]];                
                
                
                //比較取出歷史最大值與最小值
                {
                    if (issetHighLow==NO) {
                        //第一次設定
                        his_data_low=[[pdata objectAtIndex:1] doubleValue ];
                        his_data_high=[[pdata objectAtIndex:1] doubleValue ];
                        issetHighLow=YES;
                    }
                    if ([[pdata objectAtIndex:3] doubleValue ]>his_data_high) {
                        his_data_high=[[pdata objectAtIndex:3] doubleValue ];
                    }
                    if ([[pdata objectAtIndex:4] doubleValue ]<his_data_low) {
                        his_data_low=[[pdata objectAtIndex:4] doubleValue ];
                    }  
                    
                    last_his_date=dates;
                    last_his_close=close;
                }
                
                
                if (dates) {
                    [dic setObject:dates forKey: HIS_basic_date ];
                    [dic setObject:close forKey:HIS_basic_close];
                    [dic setObject:open forKey:HIS_basic_open];
                    [dic setObject:high forKey:HIS_basic_high];
                    [dic setObject:low forKey:HIS_basic_low];
                    [dic setObject:volume forKey:HIS_basic_vol];
                    [dic setObject:close forKey:HIS_basic_adjclose]; //bloomberg直接就是還原後數據
                    [outarray_his_data addObject:dic];
                }
                
                                
                
                [dic release];
                
                                                  
            }
            
            
            
            
        }
        
    }    
    //將歷史資料檔案陣列 最大值 最小值 存放在Dictionary，用來傳出去
    NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
    [out_dic setObject:code forKey:DB_object_sqlite_basic_code];
    [out_dic setObject:outarray_his_data forKey:@"his_data"];
    [out_dic setObject:[NSNumber numberWithDouble: his_data_high] forKey:@"his_data_high"];
    [out_dic setObject:[NSNumber numberWithDouble: his_data_low] forKey:@"his_data_low"];      
    [out_dic setObject:last_his_date forKey:@"last_his_date"];
    [out_dic setObject:last_his_close forKey:@"last_his_close"];
    
    return out_dic;
}


@end
